package com.khotyn.heresy.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.khotyn.heresy.bean.Album;
import com.khotyn.heresy.bean.Tag;
import com.khotyn.heresy.dao.AlbumDAO;
import com.khotyn.heresy.dao.TagDAO;
import com.khotyn.heresy.util.ListOperation;
import com.khotyn.heresy.validator.AlbumValidator;

/**
 * 修改相册的控制器, 修改：将错误语句注释，以便让其他程序运行，另外，去除Autowired注释，加入set和get语句
 * 
 * @author 王长乐
 * 
 */
@Controller
@RequestMapping("/modifyAlbum.html")
@SessionAttributes("userID")
public class ModifyAlbumController {
	@Autowired
	private AlbumDAO albumDAO; // 相册DAO
	@Autowired
	private TagDAO tagDAO; // 标签DAO
	private List<Tag> albumTags; // 图片的标签

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView setupForm(ModelMap model, @ModelAttribute("userID") Integer userID,
			@RequestParam(value = "albumID", required = false) Integer albumID) {
		if (userID == null)
			return new ModelAndView("login");

		if (albumID == null) {
			return new ModelAndView("album");
		} else {

			Album album = new Album();
			album = albumDAO.selectAlbumByID(albumID);// 通过ID获取相册对象
			setAlbumTags(album.getAlbumTags());
			return new ModelAndView("modifyAlbum", "album", album);
		}
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView onSubmit(@ModelAttribute("album") Album album, BindingResult result, @ModelAttribute("userID") Integer userID,
			@RequestParam(value = "albumTags", required = true) String albumTags, SessionStatus status, HttpServletRequest request, ModelMap map) {
		System.out.println(album.getFlagPermission());
		int errorCount = result.getErrorCount();
		if (userID == null) {
			return new ModelAndView("login");
		} else {
			album.setAlbumTags(getAlbumTags());
			new AlbumValidator().validate(album, result);

			// 检查标签的正确性
			List<String> tags = ListOperation.stringToList(albumTags, "\\s{1,}");

			if (ListOperation.filtList(tags)) {
				map.addAttribute("tagError", true);
				return new ModelAndView("modifyAlbum");
			}

			if (result.getErrorCount() != errorCount) {
				return new ModelAndView("modifyAlbum");
			} else {

				// 检查相册是否重名
				List<Album> albumList = albumDAO.selectAlbumByUserID(userID);
				Iterator<Album> iter = albumList.iterator();
				while (iter.hasNext()) {
					Album existAlbum = (Album) iter.next();

					// 如果相册是本身，则跳过不检测
					if (existAlbum.getAlbumID() == album.getAlbumID()) {
						continue;
					}

					if (existAlbum.getAlbumName().equals(album.getAlbumName())) {
						return new ModelAndView("createAlbum");
					}
				}

				List<String> tagDelete = ListOperation.minus(album.getAlbumTags(), tags); // 需要被删除的标签
				List<String> tagNew = ListOperation.minus(tags, album.getAlbumTags()); // 需要新加入的标签
				album.setAlbumTags(new ArrayList<Tag>());
				for (String str : tags) {
					Tag tag = new Tag();
					tag.setTagName(str);
					album.getAlbumTags().add(tag);
				}

				album.setPictureCount(Integer.parseInt(request.getParameter("pictureCount")));
				album.getOwner().setUserID(Integer.parseInt(request.getParameter("ownerID")));

				albumDAO.updateAlbumByID(album);

				for (String str : tagDelete) {
					tagDAO.deleteAlbumTag(album.getAlbumID(), tagDAO.selectTagByName(str).getTagID());
				}

				for (String str : tagNew) {
					Tag tag = tagDAO.selectTagByName(str);

					if (tag == null) {
						tag = new Tag();

						if (str != null && !str.trim().equals("")) {
							tag.setTagName(str);
							tagDAO.insertTag(tag);
							tag = tagDAO.selectTagByName(str);
							tagDAO.insertAlbumTag(album.getAlbumID(), tag.getTagID());
						}
					}
				}

				return new ModelAndView("redirect:/user.html");

			}

		}

	}

	public void setAlbumTags(List<Tag> albumTags) {
		this.albumTags = albumTags;
	}

	public List<Tag> getAlbumTags() {
		return albumTags;
	}
}
